package com.bwie.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bwie.mapper.TbUserMapper;
import com.bwie.pojo.TbUser;
import com.bwie.service.TbUserService;
import com.bwie.utils.MobileMessageUtil;
import com.bwie.utils.R;
import com.bwie.vo.LoginInfoVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * description:
 *
 * @Author caoshuaifeng
 * @Create 2025/3/12 9:18
 * @Version 1.0
 */
@Service
public class TbUserServiceImpl implements TbUserService {

    @Autowired
    TbUserMapper tbUserMapper;

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Override
    public R sendCode(String mobile) {
        TbUser tbUser = tbUserMapper.selectOne(new QueryWrapper<TbUser>().lambda().eq(TbUser::getUserMobile, mobile));
        if(tbUser==null){
            return R.ERROR(500,"手机号未注册，请先完成注册");
        }
        String code = RandomUtil.randomNumbers(4);
        System.out.println("验证码为："+code);
        MobileMessageUtil.sendMobileMessage(mobile,code);
        stringRedisTemplate.opsForValue().set(mobile,code,1, TimeUnit.MINUTES);
        return R.OK();
    }

    @Override
    public R login(LoginInfoVo loginInfoVo) {
        TbUser tbUser = tbUserMapper.selectOne(new QueryWrapper<TbUser>().lambda().eq(TbUser::getUserMobile, loginInfoVo.getUserMobile()));
        if(tbUser==null){
            return R.ERROR(500,"手机号不存在");
        }
        String code = stringRedisTemplate.opsForValue().get(loginInfoVo.getUserMobile());
        if(!code.equals(loginInfoVo.getUserCode())){
            return R.ERROR(500,"验证码错误");
        }
        //生成token
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "123456").claim("userId", tbUser.getUserId()).compact();
        //将token存入redis
        String tokenKey="token-"+tbUser.getUserId();
        stringRedisTemplate.opsForValue().set(tokenKey,token,15,TimeUnit.MINUTES);
        tbUser.setToken(token);
        return R.OK(tbUser);
    }

    @Override
    public R register(TbUser tbUser) {
        TbUser tbUser1 = tbUserMapper.selectOne(new QueryWrapper<TbUser>().lambda().eq(TbUser::getUserMobile, tbUser.getUserMobile()));
        if(tbUser1!=null){
            return R.ERROR(500,"手机号已注册，请直接登录");
        }
        tbUser.setBounty(30.00);
        tbUserMapper.insert(tbUser);


        return R.OK(tbUser);
    }

    @Override
    public R getUserById(Integer userId) {
        TbUser tbUser = tbUserMapper.selectById(userId);
        return R.OK(tbUser);

    }

}
